<template>
   <PanelSplitTwo bottomToolbarHeight="0" :num="2">
    <template #top>
      <SetUserSelect
        :key="keys"
        class="queryForm"
        :formData="orderSelect"
        v-model:queryParams="paginationParams"
        @selectFunc="selectFunc"
      ></SetUserSelect>
    </template>
     <template #centerToolbar>
        <div class="vex_flex">
          <el-row :gutter="20" style="margin-bottom: 10px">
            <el-col :span="1.5">
              <el-button @click="handleQuery(0)">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="handleQuery(2)">查看</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="handleQuery(1)">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="delFun">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="publishFun">发布</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="notPublishedFun">下架</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button  @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList.length !=1" @click="handleQuerys(1)">复制</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :disabled="selectedList?.length <= 0" @click="auditbatchFun">批量发布</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button  @click="autoStatusFun">刷新任务</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button @click="handleQuery">取消</el-button>
            </el-col> -->
          </el-row>
        <VxeTableGrid
          :key="keys"
          style="flex: 1;"
          :tableColumn="tableColumn"
          :tableLoading="tableLoading"
          :dataList="dataList"
          :showPagination="true"
          :paginationParams="paginationParams"
          @getList="setQueryParams"
          @selectedChange="selectedChange"
        >
        </VxeTableGrid>
      </div>
     </template>
   </PanelSplitTwo>
</template>

<script setup lang="jsx">
import { useRouter } from 'vue-router'
import { forceLogout, list as initData } from "@/api/monitor/online";
import { getprovince } from "@/api/basicManagement/hospital";
import { drugList  } from "@/api/basicManagement/varietyMana";
import { hallList, delhall, publish, notPublished, auditbatch, autostatus,  } from "@/api/taskList";
import { watch, getCurrentInstance, ref, onBeforeUnmount, onMounted } from "vue";
import { ElMessageBox } from 'element-plus'
import datas from './data.js'

let keys = ref(0);
const { paginationParams, orderSelect }  = datas
const { proxy } = getCurrentInstance();
let proxys = proxy;
const router= useRouter ()
const dialogVisible = ref(false)
const handleClose = () => {
  dialogVisible.value = false
}
onBeforeUnmount(() => {
  window.sessionStorage.setItem('setDateTimedTaskList', JSON.stringify(paginationParams.value))
})
onMounted(() => {
  if (window.sessionStorage.getItem('setDateTimedTaskList')) {
    let dateNew = JSON.parse(window.sessionStorage.getItem('setDateTimedTaskList'))
    paginationParams.value = dateNew || {}
    window.sessionStorage.removeItem('setDateTimedTaskList')
  } else {
    paginationParams.value = {
      pageNum: 1,
      pageSize: 10,
    }
  }
})
const { timed_task_type, timed_task_category, timed_task_status } = proxy.useDict("timed_task_type", "timed_task_category", "timed_task_status");
// watch(
//   timed_task_type,
//   (newV, oldV) => {
//     orderSelect[2].selectData = timed_task_type.value;
//     keys.value = new Date().getTime();
//   }
// );
// watch(
//   timed_task_category,
//   (newV, oldV) => {
//     orderSelect[3].selectData = timed_task_category.value;
//     keys.value = new Date().getTime();
//   }
// );
watch(
  timed_task_status,
  (newV, oldV) => {
    orderSelect[4].selectData = timed_task_status.value;
    keys.value = new Date().getTime();
  }
);
const drugListFun = () => {
  drugList({
    pageNum: 1,
    pageSize: 10000,
  }).then((res) => {
    res.rows?.forEach((val) => {
      val.value = val.id
      val.label = val.name
    })
    orderSelect[3].selectData = res.rows
    keys.value = new Date().getTime();
  })
}
drugListFun()
const publishFun = () => {
  if (status.value == 1 || status.value == 3) {
    publish({
      id: Id.value
    }).then((res) => {
      proxys.$modal.msgSuccess(`发布成功`);
      hospitalLists()
      keys.value = new Date().getTime()
      selectedList.value = []
    })
  } else {
    proxys.$modal.msgWarning('未发布跟下架的任务才能发布')
  }
  
}
const notPublishedFun = () => {
  if (status.value == 2 || status.value == 4) {
    notPublished({
      id: Id.value
    }).then((res) => {
      proxys.$modal.msgSuccess(`下架成功`);
      hospitalLists()
      keys.value = new Date().getTime()
      selectedList.value = []
    })
  } else {
    proxys.$modal.msgWarning('已发布的任务才能下架')
  }
  
}
const handleExport = () => {
  proxy.download("/task/hall/export", {
    ...paginationParams.value
  }, `config_${new Date().getTime()}.xlsx`);
}
const getprovinceFun = () => {
  getprovince().then((res) => {
    res.data?.forEach((val) => {
      val.value = val.cityname
      val.label = val.cityname
    })
    orderSelect[1].selectData = res.data
    keys.value = new Date().getTime();
  })
}
getprovinceFun()
const dataLists = ref([])
const tableColumn = ref([
  { type: "checkbox", width: 60, fixed: null },
  { field: "name", title: "任务名称" },
  { field: "type", title: "类型",
  slots: { default: ({ row }, h) => {
    return [<dict-tag options={ timed_task_type.value } value={ row.type }></dict-tag>]
  }} },
  // { field: "category", title: "类别",
  // slots: { default: ({ row }, h) => {
  //   return [<dict-tag options={ timed_task_category.value } value={ row.category }></dict-tag>]
  // }} },
  { field: "province", title: "省份"},
  { field: "drugName", title: "品种" },
  { field: "quantity", title: "数量"},
  { field: "appliedQty", title: "已申请数量"},
  { field: "area", title: "可申请数量", slots: { default: ({ row }, h) => {
    return row.quantity - row.appliedQty
  }}},
  { field: "startTime", title: "开始时间"},
  { field: "endTime", title: "截止时间"},
  { field: "status", title: "状态",
  slots: { default: ({ row }, h) => {
    return [<dict-tag options={ timed_task_status.value } value={ row.status }></dict-tag>]
  }} },
])
const onlineList = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
let tableLoading = ref(false)
const dataList = ref([
])

const queryParams = ref({
  ipaddr: undefined,
  userName: undefined
});
// 切换分页
  function setQueryParams(val) {
    console.log(val)
    paginationParams.pageNum = val.pageNum;
    paginationParams.pageSize = val.pageSize;
    hospitalLists()
  }
  let Id = ref('')
  let status = ref(null)
  // 选择表格
  let selectedList = ref([])
  function selectedChange(val) {
    Id.value = val.currentItem.id
    status.value = val.currentItem.status
    selectedList.value = val.selectedList
  }
/** 新增|修改 */
function handleQuery(type) {
  if (type == 2) {
    router.push({
      path: '/timedTask/taskDetails',
      query: {
        id: Id.value,
        look: 'look'
      }
    })
    return
  }
  if(type == 0){
    window.sessionStorage.removeItem('setDateTimedTask')
  }
  router.push({
      path: '/timedTask/taskDetails',
      query: {
        id: type == 1? Id.value : undefined,
        type: type == 1? undefined : 'add',
      }
    })
  // if ((status.value == 1 || status.value == 3) || type == 0) {
  //   router.push({
  //     path: '/timedTask/taskDetails',
  //     query: {
  //       id: type == 1? Id.value : undefined,
  //       type: type == 1? undefined : 'add',
  //     }
  //   })
  // } else {
  //   proxys.$modal.msgWarning('下架跟未发布的任务才能修改')
  // }
  
}

const hospitalLists = () => {
  // platformNum
  hallList({
    ...paginationParams.value,
  }).then((res) => {
    paginationParams.value.total = res.total
    dataList.value = res.rows
  })
}
hospitalLists()
const selectFunc = () => {
  paginationParams.value.pageNum = 1
  hospitalLists()
}

const handleQuerys = () => {

  router.push({
      path: '/timedTask/taskDetails',
      query: {
        id: Id.value,
        copy: 'look'
      }
    })
}
const auditbatchFun = () => {
  let sta = false
  selectedList.value.forEach((val) => {
    if (val.status != 1 && val.status != 3) {
      sta = true
    }
  })
  if (sta) {
    proxys.$modal.msgWarning('保存跟下架才能发布')
    return
  }
  let datas = selectedList.value.map(item => item.id)
  auditbatch(datas).then((res) => {
    proxys.$modal.msgSuccess(`批量发布成功`);
    hospitalLists()
  })

}

// 刷新任务
const autoStatusFun = () => {
  autostatus().then(() => {
    proxys.$modal.msgSuccess(`所有任务状态已经更新`);
    hospitalLists()
  })
}
// 删除
const delFun = () => {
  if (status.value == 1 || status.value == 3) {
    ElMessageBox.confirm('是否确认删除?')
    .then(() => {
      delhall(Id.value).then(() => {
        proxy.$modal.msgSuccess(`删除成功`);
        hospitalLists()
      })
    })
    .catch(() => {
      // catch error
    })
  } else {
    proxys.$modal.msgWarning('已保存跟下架才能删除')
  }
  
  
}
</script>
<style scoped>
  .app-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 85px);
    overflow: hidden;
  }
  .vex_flex {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
  }
  .flexmin {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
</style>